package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.bean.dto.ContractClient;
import com.hhs.storage.config.InitSystemParamRunner;
import com.hhs.storage.dao.ComsumerDao;
import com.hhs.storage.service.ComsumerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.service.ImgService;
import com.hhs.storage.util.SysUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2022-12-07
 */
@Service
@Lazy
@Transactional
public class ComsumerServiceImpl extends ServiceImpl<ComsumerDao, Comsumer> implements ComsumerService {
    @Autowired
    private InitSystemParamRunner initSystemParamRunner;
    @Autowired
    private ContractServiceImpl contractService;
    @Resource
    private ImgService imgService;
    @Override
    public Map<String, Object> getAll(InputParam inputParam) {
        QueryWrapper ew = new QueryWrapper<Comsumer>();
        if(!StringUtils.isEmpty(inputParam.getName())){
            ew.like("name",inputParam.getName());
        }
        ew.orderByDesc("create_time");
        Page<Comsumer> result = this.page(new Page<Comsumer>(
                inputParam.getPage(),
                inputParam.getSize()),ew);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", result.getRecords());
        map.put("total",result.getTotal());
        map.put("code", 1);
        return map;
    }

    @Override
    public Map<String, Object> addOrUpdate(Comsumer comsumer,String deleIdStr, MultipartFile[] qualificationCertificateList) {
        if(StringUtils.isEmpty(comsumer.getName())){
            return ResponseInfo.error("参数错误");
        }
        List<Comsumer> tempList = this.list(new QueryWrapper<Comsumer>().eq("name", comsumer.getName()));
        //新增
        if (StringUtils.isEmpty(comsumer.getId())) {

            comsumer.setCreateTime(LocalDateTime.now());
            comsumer.setId(SysUtil.UUID());
            if (tempList.size() > 0) {
                return ResponseInfo.error("名称已存在，请重新输入");
            }
            //资质有图片则保存图片
            if(qualificationCertificateList.length>0){
                imgService.upload( SysUtil.COMSUMER_QUALIFICATION_CERTIFICATE,comsumer.getId(),qualificationCertificateList);
            }
            this.save(comsumer);
        } else {//修改
            //资质有图片则保存图片
            if(qualificationCertificateList.length>0){
                imgService.upload( SysUtil.COMSUMER_QUALIFICATION_CERTIFICATE,comsumer.getId(),qualificationCertificateList);
            }

            //删除图片
            if(!StringUtils.isEmpty(deleIdStr)){
                String[] deleIdArr = deleIdStr.split(",");
                if(deleIdArr.length>0){
                    for (String id : deleIdArr) {
                        imgService.deleById(id);
                    }
                }
            }
            this.updateById(comsumer);
        }
        initSystemParamRunner.getComsumers();//重新获取
        return ResponseInfo.success(null);
    }

    @Override
    public Map dele(String id) {
        if(StringUtils.isEmpty(id)){
            return ResponseInfo.error("参数错误");
        }
        QueryWrapper<Contract> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("first_party",id);
        queryWrapper.or().eq("second_party",id);
        int total=contractService.count(queryWrapper);
        if (total>0){
            return ResponseInfo.error("客户存在相关业务，无法删除");
        }
        //找到资质的图片，删除图片
        Img img = new Img();
        img.setMainId(id);
        List<Img> imgList = imgService.getByMainId(img);
        for (Img img1 : imgList) {
            imgService.deleById(img1.getId());
        }
        this.removeById(id);
        initSystemParamRunner.getComsumers();//重新获取
        return ResponseInfo.success(null);
    }

    @Override
    public String addForContractClient(ContractClient contractClient, String createrId) {
        //将客户信息取出来，放入comsumer内，并返回id
        if(contractClient!=null && !StringUtils.isEmpty(contractClient.getName())){
            Comsumer comsumer=new Comsumer();
            comsumer.setName(contractClient.getName());
            comsumer.setRemark(contractClient.getRemark());
            //客户星级
            comsumer.setStar(contractClient.getStar());
            //客户公司联系人json串
            comsumer.setContacts(contractClient.getContacts());
            //新增
            if(StringUtils.isEmpty(contractClient.getId())){
                comsumer.setCreateTime(LocalDateTime.now());
                comsumer.setId(SysUtil.UUID());
                comsumer.setCreaterId(createrId);
            }else{
                //编辑
                comsumer.setId(contractClient.getId());
            }
            this.saveOrUpdate(comsumer);
            initSystemParamRunner.getComsumers();//重新获取
            return comsumer.getId();
        }
        return null;
    }
}
